import WxRequest from "./request"
//导入storage
import { getStorage, clearStorage } from './storage'
import { modal, toast } from './extendApi'
import {env} from './env'
const instance = new WxRequest({
    baseURL: env.baseURL,
    timeout: 15000,
    isLoading:false
})
// 在请求发送之前
instance.interceptors.request = (config) => {
    const token = getStorage('token')
    if (token) {
        config.header['token'] = token
    }
    return config
}
// 响应
instance.interceptors.response = async (response) => {
    const { isSuccess, data } = response
    if (!isSuccess) {
        wx.showToast({
            title: '网络异常请重试',
            icon: 'error'
        })
        return response
    }
    // 判断状态码
    switch (data.code) {
        case 200:
            return data
        case 208:
            const res = await modal({
                content: '鉴权失败，请重新登录',
                showCancel: false
            })
            if (res) {
                clearStorage()
                wx.navigateTo({
                    url: '/pages/login/login',
                })
            }
            return Promise.reject(response)
        default:
            toast({
                title: '程序出现异常，请联系客服或稍后重试'
            })
            return Promise.reject(response)
    }
}
// 实例化
export default instance